﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
using Sina.Altman.Weibo.SDK;
using System.Text.RegularExpressions;
using System.Windows.Navigation;
using Sina.Altman.Weibo.SDK.Objects;
using Newtonsoft.Json;
using System.IO;
using System.IO.IsolatedStorage;
using Sina.Altman.Weibo.Tools;
using Sina.Altman.Weibo.Languages;
using Sina.Altman.Weibo.Common;

namespace Sina.Altman.Weibo.Client
{
    public partial class Oauth : PhoneApplicationPage
    {
        #region 页面变量
        
        static string authCode = string.Empty;

        WebBrowser webBrowser = null;

        const string DefaultHtmlFormat = "<html><head><title>Altman</title></head><body style='text-align:center;background:#FFF;color:#000;'><br/><br/><br/>{0}</body></html>";

        bool _isLoaded = false;

        #endregion

        public Oauth()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(Oauth_Loaded);
        }

        #region Events
        
        void Oauth_Loaded(object sender, RoutedEventArgs e)
        {

            webBrowser=new WebBrowser(){IsScriptEnabled=true};

            webBrowser.Navigating += new EventHandler<NavigatingEventArgs>(webBrowser_Navigating);

            this.LayoutRoot.Children.Add(webBrowser);

            GetAuthorization();
        }

        void webBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            //截取code用于获取access_token
            string code = string.Empty;
            if (e.Uri.ToString().Contains("code="))
            {
                code = e.Uri.OriginalString.ToString().Split('=').LastOrDefault();
                if (!string.IsNullOrEmpty(code))
                {
                    authCode = code;

                    //get accesstoken
                    GetAccessToken();
                    
                    //不用再继续跳转了
                    e.Cancel = true;
                }
            }
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            GetAuthorization();
        }

        #endregion

        #region 验证操作

        /// <summary>
        /// 跳转到授权页面
        /// </summary>
        private void GetAuthorization()
        {
            string baseUri = Constants.AUTHORITY + "?client_id={0}&response_type=code&redirect_uri={1}";
            string fullUri = string.Format(baseUri, Constants.APP_KEY, Constants.DEVEPLOER_URL);

            webBrowser.Navigate(new Uri(fullUri, UriKind.RelativeOrAbsolute));
        }

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        private void GetAccessToken()
        {
            string baseUri = Constants.ACCESS_TOKEN_AUTHORITY + "?client_id={0}&client_secret={1}&grant_type=authorization_code&redirect_uri={2}&code={3}";
            string fullUri = string.Format(baseUri,Constants.APP_KEY,Constants.APP_SECRET,Constants.DEVEPLOER_URL,authCode);

            var request = WebRequest.Create(fullUri);
            request.Method = "POST";
            var inner = request.BeginGetResponse(GetAsyncResponseCallback, request);
        }

        /// <summary>
        /// 获取AccessToken的回调，获取到AccessToken后存储token，并跳转到首页
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private void GetAsyncResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest myrequest = asynchronousResult.AsyncState as HttpWebRequest;
                var response = (HttpWebResponse)myrequest.EndGetResponse(asynchronousResult);

                Stream responseStream = response.GetResponseStream();
                string resContent = "";
                using (var reader = new StreamReader(responseStream))
                {
                    resContent = reader.ReadToEnd();

                    AccessTokenInfo accessTokenInfo = null;
                    if (!string.IsNullOrEmpty(resContent))
                    {
                        accessTokenInfo = new AccessTokenInfo(resContent);
                        ISHelper.SaveSetting(Constants.User_Access_Token_SR,accessTokenInfo.AccessToken);
                        ISHelper.SaveSetting(Constants.Token,accessTokenInfo);


                        //这操作在异步线程上
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                NavigationService.Navigate(new Uri(Pages.HomePage, UriKind.Relative));
                            });
                    }
                }
                responseStream.Close();
            }
            catch (WebException e)
            {
                // Need to handle the exception
            }
        }

        #endregion

        #region Helper Method

        /// <summary>
        /// 默认加载中页面内容
        /// </summary>
        private static string DefaultHtml
        {
            get
            {
                return BuildHtml(LangResource.IsLoadingAccessPage);
            }
        }

        /// <summary>
        /// 建立默认Html页面
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private static string BuildHtml(string text)
        {
            return ConvertExtendedAscii(string.Format(DefaultHtmlFormat, text));
        }

        /// <summary>
        /// 中文乱码
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string ConvertExtendedAscii(string html)
        {
            string retVal = "";
            char[] s = html.ToCharArray();

            foreach (char c in s)
            {
                if (Convert.ToInt32(c) > 127)
                    retVal += "&#" + Convert.ToInt32(c) + ";";
                else
                    retVal += c;
            }

            return retVal;
        }

        #endregion
    }
}